//
//  AuctionViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/23.
//  Copyright © 2019 王洋. All rights reserved.
//
#import "HMSegmentedControl.h"
#import "CardGoodsItemCell.h"
#import "AuctionViewController.h"
#import "GoodDetailViewController.h"
#import "OYCountDownManager.h"
#import "AuctionTimeModel.h"

NSString *const k_AuctionProductItemSource = @"k_AuctionProductItemSource";

@interface AuctionViewController ()<UICollectionViewDelegate, UICollectionViewDataSource> {
    
    CGSize _cellSize;
    UIEdgeInsets _collectionEdge;
}

@property (strong, nonatomic) HMSegmentedControl *segmentedControl;

@property (nonatomic , strong) UICollectionView *willAuctionCollectionView;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) NSMutableArray <HomeProductItemModel *>* dataArray;

@property (nonatomic, strong) NSMutableArray <AuctionTimeModel *>* timeArray;

@property (nonatomic, strong) NSMutableArray <NSString *>* dayStringArray;

@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation AuctionViewController

- (void)dealloc {
    
    [kCountDownManager removeSourceWithIdentifier:k_AuctionProductItemSource];
    [kCountDownManager invalidate];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PP_AppWillEnterForegroundNoti" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];

    [self refreshParam];
    [self request_AuctionList];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];

    [kCountDownManager start];
    [kCountDownManager addSourceWithIdentifier:k_AuctionProductItemSource];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getHeadTimeRange];
    [self initView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForegroundRefreshNoti:) name:@"PP_AppWillEnterForegroundNoti" object:nil];
}

//修改时间进app刷新首页
-(void)enterForegroundRefreshNoti:(NSNotification *)Noti {
    [self request_AuctionList];
}

- (void)getHeadTimeRange {
    
    //排上几天的场，可配置
    self.selectIndex = 0;
    
    NSInteger count = 3;
    for (int i = 0; i < count; i++) {
        AuctionTimeModel *model = [AuctionTimeModel getTodayAfterDateWithCount:i];        
        [self.timeArray addObject:model];
    }
    
    NSMutableArray *titleArray = @[].mutableCopy;
    for (int i = 0; i < self.timeArray.count; i++) {
        [titleArray addObject:self.timeArray[i].dateString];
        [self.dayStringArray addObject:self.timeArray[i].dayString];
    }
    self.segmentedControl.sectionTitles = titleArray;
}

- (void)refreshParam {
    
    self.pageNum = 1;
    self.pageSize = 100;
}

- (void)request_AuctionList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *dayString = self.dayStringArray[self.selectIndex];
    [dic setValue:dayString forKey:@"dataTime"];
    [dic setValue:@(self.pageNum) forKey:@"curPage"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_AUCTION_LIST];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [[TTNoResultManager shareManager] hideNoResultWithView:self.willAuctionCollectionView];

        //返回data为字典
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            //请求成功
            if ([code isEqualToString:@"200"]) {
                
                NSArray *resultArray = [data valueForKey:@"data"];
                if ([resultArray isKindOfClass:[NSArray class]]) {

                    //product
                    self.dataArray = @[].mutableCopy;
                    for (int i = 0; i < resultArray.count; i++) {
                        NSDictionary *productDic = [resultArray objectAtIndex:i];
                        HomeProductItemModel *productModel = [[HomeProductItemModel alloc] init];
                        productModel.productID =    [productDic valueForKey:@"id"];
                        productModel.productName =  [productDic valueForKey:@"goodsName"];
                        productModel.productImage = [productDic valueForKey:@"coverImgPath"];
                        
                        productModel.auctionPrice = [[productDic valueForKey:@"goodsStartingPrice"] doubleValue];
                        productModel.marketPrice =  [[productDic valueForKey:@"goodsMarketPrice"] doubleValue];

                        productModel.goodDetailType =(PPGoodDetailType)[[productDic valueForKey:@"goodDetailType"] integerValue];


                        productModel.beginTimestamp =  [[productDic valueForKey:@"startTime"] doubleValue];
                        productModel.endTimestamp =    [[productDic valueForKey:@"endTime"] doubleValue];//2019-08-02
                        
                        productModel.countDownSource = k_AuctionProductItemSource;
                        
                        [self.dataArray addObject:productModel];
                    }
                    
                    if (resultArray.count == 0) {
                        WEAKSELF
                        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.willAuctionCollectionView errorCode:kTTViewStateNoData btnTitle:@"刷新看看" didPressButton:^{
                            [weakSelf request_AuctionList];
                        }];
                        
                    } else {
                        
                    }
                }
                
            } else {
                
                if (self.pageNum == 1) {
                    [self.dataArray removeAllObjects];
                }
                
                //检查到未登录
                if ([code isEqualToString:@"401"]) {
                    
                    [[TTUserModel sharedObject] initialization];
                    
                    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
                        if (isLogin) {
                            [self request_AuctionList];
                        }
                    }];
                    
                } else {
                    
                    [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                    [SVProgressHUD dismissWithDelay:1];
                    
                    [[TTNoResultManager shareManager] showNoResultWithStateInView:self.willAuctionCollectionView errorCode:kTTViewStateNoData btnTitle:@"重新加载" didPressButton:^{
                        [self request_AuctionList];
                    }];
                }
            }
            
        } else {
            
            if (self.pageNum == 1) {
                [self.dataArray removeAllObjects];
            }
            
            [SVProgressHUD showErrorWithStatus:@"返回为空"];
            [SVProgressHUD dismissWithDelay:1];
        }
        
        [self.willAuctionCollectionView reloadData];

        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
        [self.willAuctionCollectionView.mj_header endRefreshing];
        [self.willAuctionCollectionView.mj_footer endRefreshing];
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismissWithDelay:0.5];

        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_AuctionList];
        }];
        
        [self.willAuctionCollectionView.mj_header endRefreshing];
        [self.willAuctionCollectionView.mj_footer endRefreshing];
    }];
}

- (void)reloadTime {
    [kCountDownManager reloadSourceWithIdentifier:k_AuctionProductItemSource];
}

#pragma mark 初始化view
- (void)initView {
    
    self.title = @"拍品";
    CGFloat width = TTScreenWidth;
    CGFloat cellWidth;
    CGFloat distance = 5;
    cellWidth = width/2 - 2*distance;
    
    _cellSize =  CGSizeMake(cellWidth, cellWidth + 90);//35:52
    _collectionEdge = UIEdgeInsetsMake(distance, distance, distance, distance);
    
    [self.view addSubview:self.segmentedControl];
    [self.view addSubview:self.willAuctionCollectionView];
    
    self.segmentedControl.frame = CGRectMake(0 , 0, TTScreenWidth, 40);
    
    [self.willAuctionCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.segmentedControl.mas_bottom);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    [self.willAuctionCollectionView reloadData];
    
    WEAKSELF
    [self.segmentedControl setIndexChangeBlock:^(NSInteger index) {
        
        weakSelf.selectIndex = index;
        
        [weakSelf refreshParam];
        [weakSelf request_AuctionList];
        [weakSelf reloadTime];
    }];
    
}

#pragma mark collectionDelegate & dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CardGoodsItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CardGoodsItemCellID" forIndexPath:indexPath];
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
 sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return _cellSize;
}

//设置cell的位置
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section {
    return _collectionEdge;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GoodDetailViewController *detailVC = [[GoodDetailViewController alloc] init];
    detailVC.goodsID = self.dataArray[indexPath.row].productID;
    detailVC.type = self.dataArray[indexPath.row].goodDetailType;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (HMSegmentedControl *)segmentedControl {
    if (!_segmentedControl) {
        _segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"今天", @"明天",@"后天"]];
        _segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        _segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed;
        _segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName :[UIFont systemFontOfSize:13]};
        _segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName : [UIFont boldSystemFontOfSize:13]};
        _segmentedControl.selectionIndicatorColor = [UIColor redColor];
        _segmentedControl.backgroundColor = [UIColor whiteColor];
        _segmentedControl.selectionIndicatorHeight = 2;
        
    }
    return _segmentedControl;
}

- (UICollectionView *)willAuctionCollectionView {
    if (!_willAuctionCollectionView) {
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _willAuctionCollectionView  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
        _willAuctionCollectionView.delegate = self;
        _willAuctionCollectionView.dataSource = self;
        _willAuctionCollectionView.backgroundColor = PP_Default_Color_Gray_F1F1F1;
        [_willAuctionCollectionView registerNib:[UINib nibWithNibName:@"CardGoodsItemCell" bundle:nil] forCellWithReuseIdentifier:@"CardGoodsItemCellID"];
        
        WEAKSELF
        _willAuctionCollectionView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            
            [weakSelf refreshParam];
            [weakSelf request_AuctionList];
            [weakSelf reloadTime];
        }];
        
        _willAuctionCollectionView.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            
            weakSelf.pageNum ++;
            [weakSelf request_AuctionList];

        }];
    }
    return _willAuctionCollectionView;
}

- (NSMutableArray<AuctionTimeModel *> *)timeArray {
    
    if (!_timeArray) {
        _timeArray = [[NSMutableArray alloc] init];
    }
    return _timeArray;
}

- (NSMutableArray<NSString *> *)dayStringArray {
    
    if (!_dayStringArray) {
        _dayStringArray = [[NSMutableArray alloc] init];
    }
    return _dayStringArray;
}

@end
